package org.ccay.excel.importer.validate.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.ccay.excel.importer.validate.AbstractValidator;
import org.ccay.excel.importer.validate.IStatus;

/**
 * 模式匹配校验器。
 * 	
 * @author chaowangbang
 * @since Mar 27, 2012
 */
public class PatternValidator extends AbstractValidator {

	public static final String MESSAGE_KEY = "ccay.excel.validate.pattern.error";

	/**
	 * 模式字符串
	 */
	private String pattern;

	private boolean caseSensitive = true;
	
	private boolean trim = true;

	/** 
	 * 设置模式参数
	 * 
	 * @author chaowangbang
	 * @since Mar 26, 2012
	 * @param pattern
	 */
	public void setPattern(String pattern) {
		this.pattern = pattern;
	}
	
	/**
     * @return Returns whether the expression should be matched against in
     *         a case-sensitive way.  Default is <code>true</code>.
     */
    public boolean isCaseSensitive() {
        return caseSensitive;
    }

    /**
     * Sets whether the expression should be matched against in
     * a case-sensitive way.  Default is <code>true</code>.
     */
    public void setCaseSensitive(boolean caseSensitive) {
        this.caseSensitive = caseSensitive;
    }

    /**
     * @return Returns whether the expression should be trimed before matching.
     * Default is <code>true</code>.
     */
    public boolean isTrimed() {
        return trim;
    }

    /**
     * Sets whether the expression should be trimed before matching.
     * Default is <code>true</code>.
     */
    public void setTrim(boolean trim) {
        this.trim = trim;
    }

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.validate.IValidator#validate(java.lang.Object, org.ccay.excel.importer.validate.IValidationContext)
	 */
	public IStatus doValidate(Object value) {
		// if there is no value - don't do comparison
        // if a value is required, a required validator should be added to the field
        if (value == null || pattern == null) {
            return IStatus.Ok;
        }

        // XW-375 - must be a string
        if (!(value instanceof String)) {
            return IStatus.Ok;
        }

        // string must not be empty
        String str = ((String) value).trim();
        if (str.length() == 0) {
            return IStatus.Ok;
        }
        
        return doMatch((String)value);
	}
	
	/**
	 * 进行匹配。
	 * 
	 * @param value
	 * @return
	 */
	private IStatus doMatch(String value) {
		Pattern pattern;
        if (isCaseSensitive()) {
            pattern = Pattern.compile(this.pattern);
        } else {
            pattern = Pattern.compile(this.pattern, Pattern.CASE_INSENSITIVE);
        }

        String compare = value;
        if ( trim ) {
            compare = compare.trim();
        }
        Matcher matcher = pattern.matcher( compare );

        if (!matcher.matches()) {
        	return error();
        }

		return IStatus.Ok;
	}

}
